let UserManager = require("../manager/UserManager.class");
let RoomManager = require("../manager/RoomManager.class");
let Utils = require("../core/Utils");
let EventListener = require("../core/EventListener.class");
let JoinRoomState = require("../data/JoinRoomState");
let MessageId = require("./MessageId");
let MongoDBUtil = require("../utils/MongoDBUtil");
class User {
    constructor(socket) {
        let self = this;
        this.socket = socket;
        self.uid = 0;
        self.info = null;
        self.gameData = null;
        this.socket.on("message", function (message) {
            console.log("[" + Utils.getCurTimestampString() + "] " + "recv: " + message);
            let messageObj = JSON.parse(message);
            let code = messageObj.code;
            let data = messageObj.data;
            if (code === "login") {
                self.uid = data["unionid"];
                self.info = data;
                self.info.uid = self.uid;

                // 暂时处理登录消息
                // let messageObj = {};
                // messageObj.code = MessageId.Login;
                // messageObj.data = self.info;
                // self.sendMessage(messageObj);
                // 1、查询数据库
                // 2、如果数据库中不存在该用户，则创建改用户信息，如果存在则更新数据信息
                // 3、返回客户端消息
                // 4、是否断线续玩
                /**
                 * 创建一个新用户
                 * */
                var createUser = function (id) {
                    var o = {};
                    o._id = id;
                    o.login_type = 1;
                    o.client_id = 123456789;
                    o.nickname = "游客" + o.client_id;
                    o.sex = 1;
                    o.headimgurl = "";
                    o.unionid = id;
                    o.create_time = Date.now();
                    o.last_login_time = Date.now();
                    o.is_new = true;
                    return o;
                };
                let filter = {_id: self.uid};
                let update = {$set: {last_login_time: Date.now(),is_new: false}};
                MongoDBUtil.findOneAndUpdate("users", filter, update, function (result, value) {
                    console.log(JSON.stringify(value));
                    if (!result) {
                        console.log("findOneAndUpdate: " + result);
                        MongoDBUtil.insertOne("users", createUser(self.uid), function (err, value) {
                            // console.log(err);
                            console.log(value);
                            if (!err) {
                                let messageObj = {};
                                messageObj.code = MessageId.Login;
                                messageObj.data = self.info;
                                self.sendMessage(messageObj);
                            }
                        });
                    } else {
                        for (var key in value) {
                            // console.log(key,value[key])
                                self.info[key] = value[key];
                        }
                        delete self.info["create_time"];
                        delete self.info["last_login_time"];
                        delete self.info["headimgurl"];
                        delete self.info["_id"];
                        delete self.info["client_id"];
                        delete self.info["sex"];
                        delete self.info["is_new"];
                        delete self.info["login_type"];
                        delete self.info["nickname"];
                        self.info["what"] = "what";
                        console.log(self.info);
                        let messageObj = {};
                        messageObj.code = MessageId.Login;
                        messageObj.data = self.info;
                        self.sendMessage(messageObj);
                    }
                });
            } else if (code === MessageId.CreateRoom) {
                let room = RoomManager.getInstance().createRoom(data);
                if (room) {
                    let message = RoomManager.getInstance().joinRoom(self, room.getRoomId());
                    if (message.errorCode !== JoinRoomState.Success) {
                        let messageObj = {};
                        messageObj.code = MessageId.JoinRoom;
                        messageObj.data = message;
                        self.sendMessage(messageObj);
                    }
                } else {
                    console.log("【"+self.uid+"】创建房间失败！");
                }
            } else if (code === MessageId.JoinRoom) {
                let message = RoomManager.getInstance().joinRoom(self, data.roomId);
                if (message.errorCode !== JoinRoomState.Success) {
                    let messageObj = {};
                    messageObj.code = MessageId.JoinRoom;
                    messageObj.data = message;
                    self.sendMessage(messageObj);
                }
            } else {
                EventListener.getInstance().postMessage(messageObj);
            }
        });
        this.socket.on("disconnect", function () {
            UserManager.getInstance().removeUser(self);
            console.log("disconnect");
        });
        UserManager.getInstance().addUser(this);
    }

    sendMessage(messageObj) {
        this.socket.emit("message", JSON.stringify(messageObj));
        console.log("[" + Utils.getCurTimestampString() + "] " + "send: " + JSON.stringify(messageObj));
    }

    getUid() {
        return this.uid;
    }

    getInfo() {
        return this.info;
    }
}
module.exports = User;